#pragma once
#include <iostream>
#include <string>
#include <vector>

using namespace std;

const string HttpSep = "\r\n";

class HttpRequest
{
public:
    HttpRequest() : _req_blank(HttpSep)
    {
    }
    ~HttpRequest() {}
    bool GetLine(string &request, string *line)
    {
        auto pos = request.find(HttpSep);
        if (pos == string::npos)
        {
            return false;
        }
        *line = request.substr(0, pos);         // copy the line
        request.erase(0, pos + HttpSep.size()); // erase the line from the request
        return true;
    }
    void Deserialize(string &request)
    {
        string line;
        bool ok = GetLine(request, &line);
        if (!ok)
            return;
        _req_line = line; // 将第一行信息保存到_req_line中
        // 一直解析
        while (true)
        {
            bool ok = GetLine(request, &line);
            if (ok && line.empty())
            {
                _req_content = request; // http请求除了头部还有内容，所以把剩下的内容保存起来
            }
            else if (ok && !line.empty())
            {
                _req_header.push_back(line); // 将头部每一行信息保存到vector中
            }
            else
            {
                break;
            }
        }
    }
    void Debug()
    {
        cout << "req_line" << _req_line << endl;
        int count = 1;
        for (auto &line : _req_header)
        {
            cout << count++ << ":" << line << endl;
        }
        cout << "_req_blank" << _req_blank << endl;
        cout << "_req_content" << _req_content << endl;
    }

private:
    string _req_line;
    vector<string> _req_header;
    string _req_blank;
    string _req_content;
};
